package com.github.jexl;

/**
 * @author zhangcheng
 * @date 2023/5/5 17:26
 * @description
 */
import javax.script.*;

public class CompileJavaScriptTest {
    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        long l = System.currentTimeMillis();
        String script = "function run(arg){if (arg>500){return 0}else{return arg}}";
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine javaScriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        Compilable compilable = (Compilable) javaScriptEngine;
        CompiledScript compileScript = compilable.compile(script);
        for (int i = 0; i < 1000; i++) {
            System.out.println(jsRun("run", compileScript, i));
        }
        System.out.println("耗时：" + String.valueOf(System.currentTimeMillis() - l));

    }

    /**
     * @param methodName js脚本方法名
     * @param compiledScript js 编译脚本对象
     * @param args       js方法参数
     * @return
     * @throws ScriptException
     * @throws NoSuchMethodException
     */
    public static Object jsRun(String methodName, CompiledScript compiledScript, Object... args) throws ScriptException, NoSuchMethodException {

        compiledScript.eval();
        Invocable inv = (Invocable) compiledScript.getEngine();
        return inv.invokeFunction(methodName, args);


    }
}
